<template>
  <el-drawer size="564" class="jzt-drawer change_order_modal" v-model="_isOpen" @close="cancelClick">
    <template #header>
      <span class="modal_title">{{ $route.query?.reformId ? `编辑${titleText}售后单` : `创建${titleText}售后单` }}</span>
    </template>
    <el-form ref="formRef" :model="form" class="modal_form" label-position="top" :rules="rules">
      <el-form-item class="form_box">
        <span>给客户赔偿金额:</span>
        <el-input v-model="form.customerCompensationAmount" @input="handleInput">
          <template #suffix>元</template>
        </el-input>
        <div class="form_price mt20">
          <span>
            报价{{ titleText }}单合计：<span style="color: #3d3d3d">¥{{ form.quoteChangeAmount }}</span>
          </span>
          <span>
            <span v-if="customerTotalCollectionAmount < 0">需退款金额合计:</span>
            <span v-else>需收款金额合计：</span>
            <span class="price_high">¥{{ Math.abs(customerTotalCollectionAmount).toFixed(2) || 0.0 }}</span>
          </span>
        </div>
      </el-form-item>
      <div class="form_title mb20">
        <div class="title_text">基础信息(内部可见)</div>
      </div>
      <el-form-item :label="`${titleText}分类`" prop="rectificationValue">
        <el-cascader
          style="width: 100%"
          v-model="form.rectificationValue"
          :options="rectificationOptions"
          :props="{ multiple: false, label: 'reformTypeName', value: 'reformTypeId', children: 'children' }"
          clearable
          @change="handleRectification"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="是否需业主确认" prop="isOwnerConfirmationRequired" v-if="showisOwner">
        <el-radio-group v-model.number="form.isOwnerConfirmationRequired" :disabled="isNeedsure" @click="isNeedsureclick">
          <el-radio class="mr100" :value="1">是</el-radio>
          <el-radio :value="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否业主可见" prop="isVisible">
        <el-radio-group v-model.number="form.isVisible" :disabled="form.isOwnerConfirmationRequired == 1">
          <el-radio class="mr100" :value="1">是</el-radio>
          <el-radio :value="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否首次收款后开展任务和核量" prop="isFirstPaymentReceived">
        <el-radio-group v-model.number="form.isFirstPaymentReceived" :disabled="isFirststart">
          <el-radio :value="1" size="large">是</el-radio>
          <el-radio :value="0" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="`${titleText}模版`" prop="packageId">
        <el-select v-model="form.packageId" placeholder="请选择" prop="packageId">
          <el-option v-for="item in templateOptions" :key="item.packageId" :label="item.packageName" :value="item.packageId" />
        </el-select>
      </el-form-item>
      <el-form-item prop="reformDesc">
        <template #label>
          <div style="display: inline-block; width: calc(100% - 20px)">
            <div style="display: flex; justify-content: space-between">
              <span> 问题描述 </span>
              <el-button
                style="text-decoration: underline"
                link
                @click="getRectificationStandard(form.reformTypeId)"
                :disabled="!form.reformTypeId"
              >
                申请标准
              </el-button>
            </div>
          </div>
        </template>
        <el-input style="width: 100%" v-model="form.reformDesc" type="textarea" :placeholder="`问题描述`" />
      </el-form-item>
      <el-form-item prop="reformDesc">
        <template #label>
          <div style="display: inline-block; width: calc(100% - 20px)">
            <div style="display: flex; justify-content: space-between">
              <span> 解决方案 </span>
            </div>
          </div>
        </template>
        <el-input style="width: 100%" v-model="form.solution" type="textarea" :placeholder="`解决方案`" />
      </el-form-item>
      <el-form-item label="上传图片">
        <image-video-upload
          :file-list="picData"
          tip="只能上传jpg/png，且不超过10M,最大支持上传9张"
          accept=".jpg,.png"
          multiple
          :max-size="10"
          :max-length="9"
          @upload-success="uploadImage"
          @upload-remove="uploadImageRemove"
        >
          <div class="img_upload">
            <div style="font-size: 32px">+</div>
            <div style="color: #86909c">点击上传</div>
          </div>
        </image-video-upload>
      </el-form-item>
      <el-form-item label="上传视频">
        <image-video-upload
          :file-list="videoData"
          fileType="video"
          isLimitDuration
          accept=".avi,.mov,.mp4,.wmv"
          tip="只能上传avi/mov/mp4/wmv文件格式，单个不超过200M限制时长不超过60s，最大支持上传6个"
          multiple
          item-size="200px"
          item-height="120px"
          :max-size="200"
          :max-length="6"
          @upload-success="uploadVideo"
          @upload-remove="uploadVideoRemove"
        >
          <div class="video_upload">
            <div>
              <div style="font-size: 32px">+</div>
              <div style="color: #86909c">上传主视频</div>
            </div>
          </div>
        </image-video-upload>
      </el-form-item>
      <div class="form_title mb20" v-if="form.isVisible == 1">
        <div class="title_text">基础信息(业主可见)</div>
        <!-- <div class="title_opreate" @click="moreFlag = !moreFlag">
          {{ `${moreFlag ? "展开" : "收起"}` }}
          <img :class="moreFlag ? 'active_more' : ''" src="@/assets/images/triangle.png" /> -->
        <!-- </div> -->
      </div>
      <div v-if="form.isVisible == 1">
        <el-form-item prop="expectedDelayDays" label="预计延期天数">
          <el-input-number
            v-model="form.expectedDelayDays"
            :min="0"
            :max="99999"
            step-strictly
            :value-on-clear="0"
            oninput="item => (form.expectedDelayDays = item > 99999 ? 99999 : item)"
          />
        </el-form-item>
        <el-form-item :label="`${titleText}内容`" prop="ownerVisibleContent">
          <el-input v-model="form.ownerVisibleContent" type="textarea" :placeholder="`${titleText}内容`" />
        </el-form-item>
        <el-form-item label="上传图片" class="item_image_active">
          <image-video-upload
            :file-list="ownerpicData"
            tip="只能上传jpg/png，且不超过10M,最大支持上传9张"
            accept=".jpg,.png"
            multiple
            :max-size="10"
            :max-length="9"
            @upload-success="owneruploadImage"
            @upload-remove="owneruploadImageRemove"
          >
            <div class="img_upload">
              <div style="font-size: 32px">+</div>
              <div style="color: #86909c">点击上传</div>
            </div>
          </image-video-upload>
        </el-form-item>
        <el-form-item label="上传视频" class="item_video_active">
          <image-video-upload
            :file-list="ownervideoData"
            fileType="video"
            isLimitDuration
            accept=".avi,.mov,.mp4,.wmv"
            tip="只能上传avi/mov/mp4/wmv文件格式，单个不超过200M限制时长不超过60s，最大支持上传6个"
            multiple
            :max-size="200"
            :max-length="6"
            @upload-success="owneruploadVideo"
            @upload-remove="owneruploadVideoRemove"
          >
            <div class="video_upload">
              <div>
                <div style="font-size: 32px">+</div>
                <div style="color: #86909c">上传主视频</div>
              </div>
            </div>
          </image-video-upload>
        </el-form-item>
      </div>
      <div style="text-align: center">
        <el-button class="cancel_btn" @click="cancelClick">取消</el-button>
        <el-button class="confirm_btn" @click="submitConfirm">提交</el-button>
      </div>
    </el-form>

    <div class="application-dialog">
      <el-dialog v-model="isShowApplicationDialog" width="544px" :show-close="true" @close="handelApplicationCancel">
        <template #header>
          <!-- <title-view title="申请标准" isClose @close="handelApplicationCancel" /> -->
        </template>
        <el-form :model="applicationForm" v-if="isShowApplicationDialog" v-loading="isLoadingInfo">
          <el-form-item label="汇报标准">
            <el-input v-model="applicationForm.standardDesc" type="textarea" disabled :autosize="{ minRows: 4 }" />
          </el-form-item>
          <el-form-item label="上传图片">
            <image-video-upload :file-list="applicationPicData" disabled />
          </el-form-item>
          <el-form-item label="上传视频">
            <image-video-upload :file-list="applicationVideoData" disabled fileType="video" />
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </el-drawer>
</template>
<script setup>
import { ref, computed, defineEmits } from "vue";
import imageVideoUpload from "@/components/ImageVideoUpload/index.vue";
import {
  rectificationTypeTree,
  rectificationStandard,
  serviceReasonTypeTree,
  templateType,
  addreform,
  reformDetail,
  updatareform
} from "@/apis/quote-price/following";
import { ElMessage } from "element-plus";

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  customerId: { type: String, default: "" },
  contractId: { type: String, default: "" },
  afterSalesType: { type: Number, default: 1 },
  reformId: { type: String, default: "" },
  exchangeBudgetId: { type: String, default: "" },
  needPayMoney: { type: String, default: "" },
  grossProfitRate: { type: String, default: "" },
  totalPrice: { type: String, default: "" }
});

const _isOpen = computed({
  get: () => props.modelValue,
  set: newVal => emits("update:modelValue", newVal)
});

const emits = defineEmits(["update:modelValue", "cancel", "submit"]);

const formRef = ref();
const form = ref({ expectedDelayDays: 0, isOwnerConfirmationRequired: 0 });
const status = ref({});

const rectificationOptions = ref([]);
const templateOptions = ref([]);
const reasontreeData = ref([]);
const applicationForm = ref({});

const picData = ref([]);
const videoData = ref([]);
const ownerpicData = ref([]);
const ownervideoData = ref([]);
const applicationPicData = ref([]);
const applicationVideoData = ref([]);

const moreFlag = ref(true);
const isShowApplicationDialog = ref(false);
const isLoadingInfo = ref(false);
const isNeedsure = ref(false);
const showisOwner = ref(true);
const isFirststart = ref(false);

const titleText = computed(() => (props.afterSalesType === 1 ? "整改" : "增减项"));
const customerTotalCollectionAmount = computed(() => {
  return form.value.quoteChangeAmount - form.value.customerCompensationAmount;
});

const isNeedsureclick = () => {
  if (form.value.isOwnerConfirmationRequired == 0) {
    form.value.isVisible = 1;
  } else {
    form.value.isVisible = 1;
  }
};

const handleInput = value => {
  const match = value.match(/^\d{0,10}(\.\d{0,2})?/);
  const rawValue = match ? match[0] : "";
  const validValue = rawValue.length <= 13 ? rawValue : rawValue.slice(0, 13);
  form.value.customerCompensationAmount = validValue;
};

const getRectificationTypeTree = async () => {
  const { data } = await rectificationTypeTree(props.afterSalesType, 1);
  rectificationOptions.value = data;
};

const handleRectification = e => {
  form.value.reformTypeId = e[e.length - 1];
  form.value.packageId = "";
  resetRideo(form.value.reformTypeId);
};

const resetRideo = async e => {
  const { data } = await rectificationStandard(e);
  if (data.taskPackageList.length > 0) {
    templateOptions.value = data.taskPackageList;
  } else {
    getTemplateType();
  }
  // 判断 isConfirm
  isNeedsure.value = Boolean(data.isConfirm);
  form.value.isOwnerConfirmationRequired = 1;
  form.value.isVisible = 1;

  showisOwner.value = !data.isConfirm;

  // 判断 afterPay
  isFirststart.value = Boolean(data.afterPay);
  form.value.isFirstPaymentReceived = data.afterPay !== null ? (data.afterPay ? 1 : 0) : "";
};

const resetRideoUpdata = async e => {
  const { data } = await rectificationStandard(e);
  if (data.taskPackageList.length > 0) {
    templateOptions.value = data.taskPackageList;
  } else {
    getTemplateType();
  }
  isNeedsure.value = Boolean(data.isConfirm);
  isFirststart.value = Boolean(data.afterPay);
};

const getTemplateType = async () => {
  const { data } = await templateType(props.afterSalesType);
  templateOptions.value = data;
};

const handleChangeReason = e => {
  form.value.reasonIds = e[e.length - 1];
};

const getserviceReasonTypeTree = async () => {
  const { data } = await serviceReasonTypeTree(props.afterSalesType);
  reasontreeData.value = data;
};

//获取申请标准
const getRectificationStandard = async value => {
  if (!value) return;
  isShowApplicationDialog.value = true;
  try {
    isLoadingInfo.value = true;
    const { data } = await rectificationStandard(value);
    handelDetailData(data);
    applicationForm.value = data ?? {};
    isLoadingInfo.value = false;
  } catch (err) {
    isLoadingInfo.value = false;
  }
};

const handelDetailData = data => {
  const picUrls = data.picUrls ? data.picUrls.split(",") : [];
  const picIds = data.picIds ? data.picIds.split(",") : [];
  const videoUrls = data.videoUrls ? data.videoUrls.split(",") : [];
  const videoIds = data.videoIds ? data.videoIds.split(",") : [];
  applicationPicData.value = picUrls.map((item, index) => {
    return {
      fileUrl: item,
      fileName: "",
      fileId: picIds[index]
    };
  });
  applicationVideoData.value = videoUrls.map((item, index) => {
    return {
      fileUrl: item,
      fileName: "",
      fileId: videoIds[index]
    };
  });
};

const handelApplicationCancel = () => {
  isShowApplicationDialog.value = false;
  applicationForm.value = {
    standardDesc: "",
    picUrls: "",
    picIds: "",
    videoUrls: "",
    videoIds: ""
  };
  applicationPicData.value = [];
  applicationVideoData.value = [];
};

const uploadImage = data => {
  picData.value.push({
    ...data
  });
};

const uploadImageRemove = index => {
  picData.value.splice(index, 1);
};

const uploadVideo = data => {
  videoData.value.push({
    ...data
  });
};

const uploadVideoRemove = index => {
  videoData.value.splice(index, 1);
};

const owneruploadImage = data => {
  ownerpicData.value.push({
    ...data
  });
};

const owneruploadImageRemove = index => {
  ownerpicData.value.splice(index, 1);
};

const owneruploadVideo = data => {
  ownervideoData.value.push({
    ...data
  });
};

const owneruploadVideoRemove = index => {
  ownervideoData.value.splice(index, 1);
};

const submitConfirm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async valid => {
    if (valid) {
      const joinList = (item, propName) => item.map(item => item[propName]).join(",");

      form.value.picIds = joinList(picData.value, "fileId");
      form.value.picUrls = joinList(picData.value, "fileUrl");
      form.value.videoIds = joinList(videoData.value, "fileId");
      form.value.videoUrls = joinList(videoData.value, "fileUrl");

      if (form.value.isVisible == 1) {
        form.value.ownerVisiblePicIds = joinList(ownerpicData.value, "fileId");
        form.value.ownerVisiblePicUrls = joinList(ownerpicData.value, "fileUrl");
        form.value.ownerVisibleVideoIds = joinList(ownervideoData.value, "fileId");
        form.value.ownerVisibleVideoUrls = joinList(ownervideoData.value, "fileUrl");
      } else {
        form.value.expectedDelayDays = 0;
        form.value.ownerVisibleContent = "";
      }

      if (props.reformId) {
        await updatareform(props.reformId, form.value);
        ElMessage.success("更新成功");
      } else {
        form.value.contractId = props.contractId;
        form.value.customerId = props.customerId;
        form.value.exchangeBudgetId = props.exchangeBudgetId;
        form.value.afterSalesType = props.afterSalesType;

        await addreform(form.value);
        ElMessage.success("新增成功");
      }
      _isOpen.value = false;
    } else {
      console.log("提交失败，请检查输入内容");
      return false;
    }
  });
};

const cancelClick = () => {
  emits("update:modelValue", false);
};

const getReformDetail = async () => {
  const { data } = await reformDetail(props.reformId);
  form.value = { ...data };
  resetRideoUpdata(data.reformTypeId);
  form.value.rectificationValue = findParentIds(rectificationOptions.value, data.reformTypeId, "reformTypeId");
  videoData.value = parseMediaData(data.videoIds, data.videoUrls);
  picData.value = parseMediaData(data.picIds, data.picUrls);
  if (data.ownerVisibleVideoIds) {
    ownervideoData.value = parseMediaData(data.ownerVisibleVideoIds, data.ownerVisibleVideoUrls);
  }
  if (data.ownerVisiblePicIds) {
    ownerpicData.value = parseMediaData(data.ownerVisiblePicIds, data.ownerVisiblePicUrls);
  }
};

const parseMediaData = (ids, urls) => {
  const idArray = ids ? ids.split(",") : [];
  const urlArray = urls ? urls.split(",") : [];
  if (idArray.length !== urlArray.length) {
    console.warn("ID 和 URL 数量不匹配");
  }
  return idArray.map((id, index) => ({
    fileId: id,
    fileUrl: urlArray[index] || "" // 防止访问 undefined
  }));
};

const findParentIds = (nodes, targetId, key) => {
  const path = [];
  const search = nodeList => {
    for (const node of nodeList) {
      path.push(node[key]);
      if (node[key] === targetId) {
        return true;
      }
      if (node.children && search(node.children)) {
        return true;
      }
      path.pop();
    }
    return false;
  };
  search(nodes);
  return path;
};

(async () => {
  form.value.customerCompensationAmount = "0";
  form.value.projectedGrossMargin = props.grossProfitRate || "0";
  props.afterSalesType === 3 && (titleText.value = "增减项");

  await getRectificationTypeTree();
  await getserviceReasonTypeTree();

  if (props.reformId) await getReformDetail();
  form.value.quoteChangeAmount = props.needPayMoney || "0";
})();

const rules = {
  rectificationValue: [{ required: true, message: "请选择分类", trigger: "change" }],
  isVisible: [{ required: true, message: "请选择是否业主可见", trigger: "change" }],
  reasontreeValue: [{ required: true, message: "请选择原因", trigger: "change" }],
  isOwnerConfirmationRequired: [{ required: true, message: "请选择是否需要业主确认", trigger: "blur" }],
  packageId: [{ required: true, message: "请选择模板", trigger: "blur" }],
  isFirstPaymentReceived: [{ required: true, message: "请选择是否首次收款后开展任务和核量", trigger: "blur" }],
  reformDesc: [{ required: true, message: "内容不能为空", trigger: "blur" }],
  ownerVisibleContent: [{ required: true, message: "内容不能为空", trigger: "blur" }]
};
</script>
<style lang="scss">
.change_order_modal {
  .el-drawer__header {
    margin-bottom: 0;
  }
  .el-form-item__label {
    color: #4e5969;
    padding: 0 !important;
  }
  .modal_title {
    font-size: 18px;
    line-height: 24px;
    color: #131414;
  }
  .modal_form {
    .form_box {
      padding: 10px;
      background: #f6f8fa;
      border-radius: 10px 0px 0px 10px;

      .form_price {
        width: 100%;
        display: flex;
        justify-content: space-between;
        color: #606266;
        .price_high {
          color: #ff3333;
        }
      }
      .el-input__wrapper {
        background: white !important;
      }
    }
    .form_title {
      display: flex;
      justify-content: space-between;
      .title_text {
        font-size: 18px;
        line-height: 24px;
      }
      .title_opreate {
        color: #213270;
        display: flex;
        align-items: center;
        gap: 5px;
        cursor: pointer;
        transform: rotate(0deg);
        img {
          transition: all 250ms linear;
        }
        .active_more {
          transform: rotate(180deg);
        }
      }
    }
    .form_extra {
      display: none;
    }
    .active_extra {
      display: block;
    }
    .img_upload {
      box-sizing: border-box;
      padding: 10px;
      width: 80px;
      height: 80px;
      background: #f2f3f5;
      text-align: center;
      color: #c9cdd4;
    }
    .video_upload {
      display: flex;
      align-items: center;
      justify-content: center;
      box-sizing: border-box;
      padding: 10px;
      width: 200px;
      height: 120px;
      background: #f2f3f5;
      text-align: center;
      color: #c9cdd4;
    }
  }
  .cancel_btn,
  .confirm_btn {
    width: 120px;
    height: 36px !important;
    border: 0 !important;
    border-radius: 2px !important;
  }
  .cancel_btn {
    background: #f2f3f5 !important;
    color: #1d2129 !important;
  }
  .confirm_btn {
    background: #424e66 !important;
    color: white !important;
  }
}
</style>
